/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.cxmx.escort.common.codec;


import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.util.Random;

/**
 * MD5不可逆加密工具类
 *
 * @author ThinkGem
 */
public class Md5Utils {

    private static final String MD5 = "MD5";
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final String Salthelmet = "helmet";
    private static final String SalthelSTR = "0A2B3C4D5E6F78G9H";


    /**
     * 加盐MD5加密
     * <p>
     *
     * @Title : getSaltMD5
     * </p>
     * <p>
     * @Description : TODO
     * </p>
     * <p>
     * @Author : HuaZai
     * </p>
     * <p>
     * @Date : 2017年12月27日 上午11:21:00
     * </p>
     */
    public static String getSaltMD5(String password) {
        // 生成一个16位的随机数
        Random random = new Random();
        StringBuilder sBuilder = new StringBuilder(16);
        sBuilder.append(Salthelmet).append(SalthelSTR);
        int len = sBuilder.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sBuilder.append("0");
            }
        }
        // 生成最终的加密盐
        String Salt = sBuilder.toString();
        password = md5Hex(password + Salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = Salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return String.valueOf(cs);
    }

    private static String md5Hex(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes());
            return new String(new Hex().encode(digest));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
            return "";
        }
    }

    public static void main(String[] args) {
        System.out.println(getSaltMD5("123456"));
    }

}
